
<template>
  <el-row>
    <el-col :span="12">
      <div class="grid-content ep-bg-purple-dark" />
      <el-card>
        <el-button type="success" style="margin-bottom:10px;" @click="exportExcel">下载</el-button>
        <el-button type="success" style="margin-bottom:10px;" @click="addDialogshow = true;">添加</el-button>
        <el-table :data="departmentList" border style="width: 100%">
          <el-table-column prop="did" label="ID" width="50px" />
          <el-table-column prop="dname" label="部门名称" />
          <el-table-column prop="dphone" label="部门电话" />
          <el-table-column label="部门人员">
            <template #default="scope">
              <span v-if="scope.row.emps && scope.row.emps.length > 0">
                <span @mouseenter="showTooltip = true; tooltipContent = scope.row.emps.map(item => item.rname).join(', ')" @mouseleave="showTooltip = false">{{ scope.row.emps[0]?.rname || '无' }}{{ scope.row.emps.length > 1? '...' : '' }}</span>
              </span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button size="small" type="primary" @click="selectBydid(scope.row.did)">修改</el-button>
              <el-popconfirm title="你确定要删除嘛" confirm-button-text="确认" cancel-button-text="取消" @confirm="deleteByDid(scope.row.did)">
                <template #reference>
                  <el-button size="small" type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-col>
  </el-row>
  <!-- 添加部门的对话框开始 -->
  <el-dialog v-model="addDialogshow" title="添加部门" width="500">
    <el-form ref="form" :model="departmentAdd" :rules="loginRules" >
      <el-form-item label="部门名称" label-width="20%" prop="dname">
        <el-input v-model="departmentAdd.dname" vautocomplete="off" @blur="handleBlur('dname')" />
      </el-form-item>
      <el-form-item label="部门电话" label-width="20%" prop="dphone">
        <el-input v-model="departmentAdd.dphone" autocomplete="off" @blur="handleBlur('dphone')" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addDialogshow = false">取消</el-button>
        <el-button type="primary" @click="insert">确认</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 添加部门的对话框结束 -->
  <!-- 修改部门的对话框开始 -->
  <el-dialog v-model="updateDialogShow" title="修改部门" width="500">
    <el-form>
      <el-form-item label="部门名称" label-width="20%">
        <el-input v-model="departmentUpdate.dname" vautocomplete="off" />
      </el-form-item>
      <el-form-item label="部门电话" label-width="20%">
        <el-input v-model="departmentUpdate.dphone" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="updateDialogShow = false">取消</el-button>
        <el-button type="primary" @click="update">确认</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 修改部门的对话框结束 -->
  <el-tooltip v-if="showTooltip" effect="dark" placement="top">
    <div slot="content" style="border: 1px solid #409EFF; padding: 5px;">{{ tooltipContent }}</div>
  </el-tooltip>
</template>

<script setup>
import departmentApi from '@/api/departmentApi';
import { reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { ElLoading } from 'element-plus';
import *as XLSX from 'xlsx';
import { saveAs } from 'file-saver';
import RepairTaskApi from "@/api/RepairTaskApi.js";
// 保存部门信息的数组
const departmentList = ref([]);
// 添加对话框是否显示状态
const addDialogshow = ref(false);
// 修改对话框是否显示状态
const updateDialogShow = ref(false);
// 被添加部门的信息
const departmentAdd = ref({
  dname: '',
  dphone: '',
});
// 被修改部门的信息
const departmentUpdate = ref({
  did: 0,
  dname: '',
  dphone: '',
});
function exportExcel() {
  const filteredData = departmentList.value.map(item => ({
    '部门id': item.did,
    '部门名称': item.dname,
    '部门电话': item.dphone,
    '部门人员': item.emps ? item.emps.map(person => person.rname).join(', ') : '暂无人员'
  }));

  const ws = XLSX.utils.json_to_sheet(filteredData);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

  const wbout = XLSX.write(wb, {
    bookType: "xlsx",
    bookSST: true,
    type: "array"
  });

  try {
    saveAs(new Blob([wbout], { type: "application/octet-stream" }), "用户.xlsx");
  } catch (e) {
    if (typeof console !== "undefined") console.log(e, wbout);
  }
}
// 定义方法根据 id 查询部门的信息
function selectBydid(did) {
  departmentApi.selectById(did).then((resp) => {
    departmentUpdate.value = resp.data;
    // 显示修改对话框
    updateDialogShow.value = true;
  });
}

// 定义方法实现部门修改
function update() {
  const loading = ElLoading.service({
    lock: true,
    text: '加载中~~~',
    background: 'rgba(0, 0, 0, 0.7)',
  });
  departmentApi.update(departmentUpdate.value).then((resp) => {
    loading.close();
    if (resp.code === 10000) {
      // 弹出消息
      ElMessage({
        message: resp.msg,
        type: 'success',
        duration: 1200,
      });
      updateDialogShow.value = false;
      selectAll();
    } else {
      ElMessage({
        message: resp.msg,
        type: 'error',
        duration: 2000,
      });
    }
  });
}

// 定义方法完成部门添加
function insert() {
  const loading = ElLoading.service({
    lock: true,
    text: '加载中~~~',
    background: 'rgba(0, 0, 0, 0.7)',
  });
  departmentApi.insert(departmentAdd.value).then((resp) => {
    loading.close();
    if (resp.code === 10000) {
      // 弹出消息
      ElMessage({
        message: resp.msg,
        type: 'success',
        duration: 1200,
      });
      // 隐藏对话框
      addDialogshow.value = false;
      // 清空对话框的数据
      departmentAdd.value = {
        dname: '',
        dphone: '',
      };
      selectAll();
    } else {
      // 弹出消息
      ElMessage({
        message: resp.msg,
        type: 'error',
        duration: 2000,
      });
    }
  });
}

function selectAll() {
  departmentApi.selectAll().then((resp) => {
    departmentList.value = resp.data;
  });
}

// 定义方法根据部门 id 删除部门
function deleteByDid(did) {
  const loading = ElLoading.service({
    lock: true,
    text: '加载中~~~',
    background: 'rgba(0, 0, 0, 0.7)',
  });
  departmentApi.delete(did).then((resp) => {
    loading.close();
    if (resp.code === 10000) {
      // 弹出消息
      ElMessage({
        message: resp.msg,
        type: 'success',
        duration: 1200,
      });
      // 刷新表格
      selectAll();
    } else {
      // 弹出消息
      ElMessage({
        message: resp.msg,
        type: 'error',
        duration: 2000,
      });
    }
  });
}

selectAll();
// 错误信息
const errors = ref({
  dname: '',
  dphone: ''
});
// 表单校验规则
const loginRules = {
  dname: [{ required: true, message: '部门名称不能为空', trigger: 'blur' }],
  dphone: [{ required: true, message: '部门电话不能为空', trigger: 'blur' }]
};
// 引用 form 实例
const form = ref(null);

const handleBlur = (field) => {
  form.value.validateField(field, (error) => {
    if (error) {
      errors.value[field] = error.message;
    } else {
      errors.value[field] = '';
    }
  });
};
// 用于控制 tooltip 的显示
const showTooltip = ref(false);
// 存储 tooltip 的内容
const tooltipContent = ref('');
</script>

<style scoped></style>